import 'package:flutter/cupertino.dart';

class YearMonthPicker extends StatefulWidget {
  final DateTime initialDate;
  final Function(DateTime) onDateSelected;

  const YearMonthPicker({
    Key? key,
    required this.initialDate,
    required this.onDateSelected,
  }) : super(key: key);

  @override
  YearMonthPickerState createState() => YearMonthPickerState();
}

class YearMonthPickerState extends State<YearMonthPicker> {
  late int _currentYear;
  late int _currentMonth;
  late FixedExtentScrollController _yearScrollController;
  late FixedExtentScrollController _monthScrollController;

  @override
  void initState() {
    super.initState();
    _currentYear = widget.initialDate.year;
    _currentMonth = widget.initialDate.month;
    _yearScrollController =
        FixedExtentScrollController(initialItem: _currentYear - 1900);
    _monthScrollController =
        FixedExtentScrollController(initialItem: _currentMonth - 1);
  }

  @override
  void dispose() {
    super.dispose();
    _yearScrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 200,
      child: Row(
        children: [
          Expanded(
            child: CupertinoPicker.builder(
              itemExtent: 32.0,
              scrollController: _yearScrollController,
              onSelectedItemChanged: (int index) {
                setState(() {
                  _currentYear = index + 1900;
                  widget.onDateSelected(DateTime(_currentYear, _currentMonth));
                });
              },
              itemBuilder: (BuildContext context, int index) {
                return Center(
                  child: Text(
                    '${index + 1900}年',
                    style: const TextStyle(fontSize: 16.0),
                  ),
                );
              },
              childCount: 200, // 可以选择的年份范围
            ),
          ),
          Expanded(
            child: CupertinoPicker.builder(
              itemExtent: 32.0,
              scrollController: _monthScrollController,
              onSelectedItemChanged: (int index) {
                setState(() {
                  _currentMonth = index + 1;
                  widget.onDateSelected(DateTime(_currentYear, _currentMonth));
                });
              },
              itemBuilder: (BuildContext context, int index) {
                return Center(
                  child: Text(
                    '${index + 1}月',
                    style: const TextStyle(fontSize: 16.0),
                  ),
                );
              },
              childCount: 12, // 固定为 12, 因为只有 12 个月
            ),
          ),
        ],
      ),
    );
  }
}
